class SoTransactionsController < ApplicationController
  before_action :set_so_transaction, only: [:show, :edit, :update, :destroy]
  before_action :set_page_title
  
  respond_to :html
  def index
    # @so_transactions = SoTransaction.page(params[:page])
    @so_transactions = SoTransaction.where(build_search(search_params)).order(created_at: :desc).page(params[:page])

    respond_to do |format|
      format.html{}
      format.json {render json:@so_transactions }
    end
  end

  def show
    @order = Order.new
    @payment = Payment.new
    @payments = Payment.where(tx_code:@so_transaction.code)
    respond_with(@so_transaction)
  end

  def new
    @so_transaction = SoTransaction.new
    respond_with(@so_transaction)
  end

  def edit
  end

  def create
    @so_transaction = SoTransaction.new(so_transaction_params)
    @so_transaction.set_code

    respond_to do |format|
      if @so_transaction.save
        format.html { redirect_to so_transactions_path, notice: 'Sales transaction was successfully created.' }
        format.json { render :show, status: :created, location: @so_transaction }
      else
        format.html { render :new }
        format.json { render json: @so_transaction.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    @so_transaction.update(so_transaction_params)
    respond_with(@so_transaction)
  end

  def destroy
    @so_transaction.destroy

    respond_to do |format|
      format.html {redirect_to so_transactions_path, notice: 'Sales transaction was successfully deleted.' }
      format.json { head :no_content }
    end
  # respond_with(@so_transaction)
  end

  private

  def set_so_transaction
    @so_transaction = SoTransaction.find(params[:id])
  end

  def so_transaction_params
    params.require(:so_transaction).permit(:code,:amount, :date, :customer_id)
  end

  def search_params
    if params[:so_transaction].present?
      so_transaction_params.permit(:code,:date, :customer_id)
    end
  end
  
  def set_page_title
    @page_title = "流水管理"
  end
  
end
